import jwt
from rest_framework import status

from Lab301 import settings
from Utils.BaseResponse import BaseResponse


def get_username_from_request(auth_header):
    if not auth_header:
        return BaseResponse(status=status.HTTP_401_UNAUTHORIZED).fail("Unauthorized")

    prefix, token_or_credentials = auth_header.split(maxsplit=1)
    if prefix.lower() == 'bearer':
        try:
            decoded_payload = jwt.decode(token_or_credentials, settings.SECRET_KEY, algorithms=['HS256'])
        except jwt.exceptions.DecodeError:
            return BaseResponse(status=status.HTTP_401_UNAUTHORIZED).fail("Unauthorized or invalid token")

        if 'username' not in decoded_payload:
            return BaseResponse(status=status.HTTP_401_UNAUTHORIZED).fail("Invalid token - missing username")

        username = decoded_payload['username']
        return username
    else:
        return None
